package br.com.ViewBuscaProduto;

import br.com.controler.ProdutoControler;
import br.com.modelo.Produto;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;
import javax.swing.AbstractAction;
import javax.swing.JComponent;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author Gilberto 13/06/2012
 */
public class BuscaProduto extends javax.swing.JDialog {

    List<Produto> listProdutos = new ArrayList<>();
    //controle
    private static Boolean selecionou = false;

    public BuscaProduto(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        listProdutos = ProdutoControler.retornaProdutos();
        populaTabelaProduto();
        // ocultando a coluna do codigo do produto
        jTable1.getColumnModel().removeColumn(jTable1.getColumnModel().getColumn(0));

        //atalhso botões
        CancelaAction cancelaAction = new CancelaAction();
        btCancela.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), "cancelaAction");
        btCancela.getActionMap().put("cancelaAction", cancelaAction);

        ConfirmaAction confirmaAction = new ConfirmaAction();
        btConfirma.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), "confirmaAction");
        btConfirma.getActionMap().put("confirmaAction", confirmaAction);

        BuscaAction buscaAction = new BuscaAction();
        btPesquisa.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F2, 0), "confirmaAction");
        btPesquisa.getActionMap().put("confirmaAction", buscaAction);

        textBusca.requestFocus();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        textBusca = new javax.swing.JTextField();
        btPesquisa = new javax.swing.JButton();
        btCancela = new javax.swing.JButton();
        btConfirma = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Lista de produtos"));
        jPanel1.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jTable1.setAutoCreateRowSorter(true);
        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "ID", "Codigo Barras", "Codigo Interno", "Descrição", "Valor", "Qtd.Estoque"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTable1.setRowHeight(20);
        jTable1.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jTable1.getTableHeader().setReorderingAllowed(false);
        jTable1.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTable1KeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTable1KeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(jTable1);
        jTable1.getColumnModel().getColumn(1).setMinWidth(125);
        jTable1.getColumnModel().getColumn(1).setPreferredWidth(125);
        jTable1.getColumnModel().getColumn(1).setMaxWidth(125);
        jTable1.getColumnModel().getColumn(2).setMinWidth(100);
        jTable1.getColumnModel().getColumn(2).setPreferredWidth(100);
        jTable1.getColumnModel().getColumn(2).setMaxWidth(100);
        jTable1.getColumnModel().getColumn(4).setMinWidth(80);
        jTable1.getColumnModel().getColumn(4).setPreferredWidth(80);
        jTable1.getColumnModel().getColumn(4).setMaxWidth(80);
        jTable1.getColumnModel().getColumn(5).setMinWidth(90);
        jTable1.getColumnModel().getColumn(5).setPreferredWidth(90);
        jTable1.getColumnModel().getColumn(5).setMaxWidth(90);

        jPanel1.add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 20, 680, 340));

        getContentPane().add(jPanel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 700, 370));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Informe dados para localização"));
        jPanel2.setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        jLabel1.setText("Procurar por: ");
        jPanel2.add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(7, 20, 80, -1));

        textBusca.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        textBusca.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                textBuscaKeyPressed(evt);
            }
        });
        jPanel2.add(textBusca, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 40, 510, 30));

        btPesquisa.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgBotoes/21botaoPesquisa.png"))); // NOI18N
        btPesquisa.setText("Localizar (F2)");
        btPesquisa.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btPesquisaActionPerformed(evt);
            }
        });
        jPanel2.add(btPesquisa, new org.netbeans.lib.awtextra.AbsoluteConstraints(530, 40, 160, 30));

        getContentPane().add(jPanel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 380, 700, 80));

        btCancela.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgBotoes/botaoCancelar.png"))); // NOI18N
        btCancela.setText("Cancelar (ESC)");
        btCancela.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btCancelaActionPerformed(evt);
            }
        });
        getContentPane().add(btCancela, new org.netbeans.lib.awtextra.AbsoluteConstraints(520, 470, 140, -1));

        btConfirma.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/imgBotoes/botaoConfirmar.png"))); // NOI18N
        btConfirma.setText("Confirmar (F12)");
        btConfirma.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btConfirmaActionPerformed(evt);
            }
        });
        getContentPane().add(btConfirma, new org.netbeans.lib.awtextra.AbsoluteConstraints(380, 470, 140, -1));

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-708)/2, (screenSize.height-534)/2, 708, 534);
    }// </editor-fold>//GEN-END:initComponents

    private void btPesquisaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btPesquisaActionPerformed
        RealizaBusca();
    }//GEN-LAST:event_btPesquisaActionPerformed

    private void btCancelaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btCancelaActionPerformed
        sair();
    }//GEN-LAST:event_btCancelaActionPerformed

    private void btConfirmaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btConfirmaActionPerformed
        sair();
    }//GEN-LAST:event_btConfirmaActionPerformed

    private void jTable1KeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            evt.consume();
            selecionou = true;
            dispose();
        } else if (evt.getKeyCode() == KeyEvent.VK_UP && jTable1.getSelectedRow() == 0) {
            textBusca.requestFocus();
        }
    }//GEN-LAST:event_jTable1KeyPressed

    private void jTable1KeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTable1KeyReleased
    }//GEN-LAST:event_jTable1KeyReleased

    private void textBuscaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_textBuscaKeyPressed
        if (evt.getKeyCode() == KeyEvent.VK_DOWN) {
            jTable1.changeSelection(0, 0, false, false);
            jTable1.requestFocus();
        }
    }//GEN-LAST:event_textBuscaKeyPressed

    public static void main(String args[]) {
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BuscaProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BuscaProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BuscaProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BuscaProduto.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                BuscaProduto dialog = new BuscaProduto(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btCancela;
    private javax.swing.JButton btConfirma;
    private javax.swing.JButton btPesquisa;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField textBusca;
    // End of variables declaration//GEN-END:variables

    private void populaTabelaProduto() {
        DefaultTableModel modelo = (DefaultTableModel) jTable1.getModel();
        while (jTable1.getRowCount() > 0) {
            modelo.removeRow(0);
        }
        NumberFormat decimal = NumberFormat.getCurrencyInstance();
        NumberFormat number = NumberFormat.getNumberInstance();

        if (!listProdutos.isEmpty()) {
            for (Produto v : listProdutos) {
                modelo.addRow(new String[]{"" + v.getId(), v.getGtin(), v.getCodigoInterno(), v.getDescricao(), decimal.format(v.getValorVenda()).toString(), number.format(v.getQtdEstoque()).toString()});
            }
        } else {
            modelo.addRow(new String[]{"0", "Nenhum registro encontrado!"});
        }
    }

    private class ConfirmaAction extends AbstractAction {

        public ConfirmaAction() {
        }

        public void actionPerformed(ActionEvent e) {
            selecionou = true;
            sair();
        }
    }

    private class CancelaAction extends AbstractAction {

        public CancelaAction() {
        }

        public void actionPerformed(ActionEvent e) {
            selecionou = false;
            sair();
        }
    }

    private class BuscaAction extends AbstractAction {

        public BuscaAction() {
        }

        public void actionPerformed(ActionEvent e) {
            RealizaBusca();
        }
    }

    private void sair() {
        dispose();
    }

    private void RealizaBusca() {
        listProdutos = ProdutoControler.retornaProdutosPesquisa(textBusca.getText());
        populaTabelaProduto();
        jTable1.changeSelection(0, 0, false, false);
        jTable1.requestFocus();
    }

    public String getProduto() {
        if (selecionou) {
            if (jTable1.getSelectedRow() != -1) {
                AbstractTableModel modelo = (AbstractTableModel) jTable1.getModel();
                return ((String) modelo.getValueAt(jTable1.getSelectedRow(), 0));//id do produto
            } else {
                JOptionPane.showMessageDialog(this, "Nenhum produto selecionado!", "Aviso do Sistema", JOptionPane.ERROR_MESSAGE);
                return "";
            }
        } else {
            return null;
        }
    }
}
